package com.wang.mvchain.outer.service.implay;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.HmacUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.HTTPUtil;
import com.wang.mvchain.outer.enums.TradeEnum;
import com.wang.mvchain.outer.service.ITradeService;

/**
 * btctrade的API工具
 * 
 * @author wangsh
 *
 */
public class BtcTradeTradeServiceImplay extends BaseTradeService implements ITradeService
{
	private String serverUrl = "http://api.btctrade.im" ; 
	
	//登陆验证的信息,可从网站模板中查找
	private JSONObject authJSON;
	@Override
	public int findWebsiteId()
	{
		return 17;
	}
	
	/**
	 * 获取签名方式
	 * 
	 * @return
	 */
	private String authSign(Map<String, String> condMap)
	{
		StringBuffer sb = new StringBuffer();
		for (Iterator iterator = condMap.entrySet().iterator(); iterator
				.hasNext();)
		{
			Entry me = (Entry) iterator.next();
			String key = me.getKey() + "";
			String value = me.getValue() + "";
			if ("requestURL".equalsIgnoreCase(key))
			{
				continue;
			}
			sb.append(key + "=" + value + "&");
		}
		if (sb.toString().lastIndexOf("&") != -1)
		{
			sb.delete(sb.lastIndexOf("&"), sb.length());
		}
		//ConstatFinalUtil.OUTER_LOG.info(sb);
		/*return EncryptUtil.hmacSHA256(sb.toString(), EncryptUtil.MD5(authJSON.get("secret") + "").toLowerCase());*/
		String sign = "" ;
		sign = HmacUtils.hmacSha256Hex(DigestUtils.md5Hex(authJSON.get("secret") + ""), sb.toString());
		return sign ; 
	}
	
	/**
	 * 获取用户基本信息
	 * {"uid":775239,"nameauth":1,"moflag":"1","btc_balance":0,"btc_reserved":0,"ltc_balance":0,"ltc_reserved":0,"doge_balance":0,"doge_reserved":0,"ybc_balance":0,"ybc_reserved":0,"cny_balance":0,"cny_reserved":0}
	 * @return
	 */
	public JSONObject getUserInfo(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
				
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new TreeMap<String, String>();
		requestMap.put("requestURL", this.serverUrl + "/api/v1/balance/");
		requestMap.put("key", authJSON.get("key") + "");
		
		String nonce = this.findReqtime();
		requestMap.put("nonce", nonce);
		
		String signature = authSign(requestMap);
		requestMap.put("signature", signature);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodPost(Collections.EMPTY_MAP , requestMap);
			ConstatFinalUtil.SYS_LOG.error(result);
			responseJSON = (JSONObject) JSON.parse(result);
			
			JSONObject responseDataJSON = (JSONObject) responseJSON.get("data");
			JSONObject dataJSON = new JSONObject();
			JSONObject balanceJSON = new JSONObject();
			JSONObject fundJSON = new JSONObject();
			
			for (Iterator iterator = responseDataJSON.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "" ; 
				String value = me.getValue() + "";
				if(key.indexOf("_balance") != -1)
				{
					key = key.substring(0 , key.indexOf("_balance"));
					balanceJSON.put(key, value);
				}else if(key.indexOf("_lock") != -1)
				{
					key = key.substring(0 , key.indexOf("_lock"));
					fundJSON.put(key, value);
				}
			}
			
			dataJSON.put("balance", balanceJSON);
			dataJSON.put("fund", fundJSON);
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			//ConstatFinalUtil.OUTER_LOG.info(this.findid() + "获取用户信息返回.----" + responseJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户信息失败."
					+ paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 下单交易
	 * 
	 * @return
	 */
	public JSONObject trade(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.trade(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new HashMap<String, String>();
		//转换货币类型
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype"));
		String [] moneytypes = moneytype.split("\\|");
		
		requestMap.put("requestURL", this.serverUrl + "/api/v1/trust_add/region/" + moneytypes[1]);
		requestMap.put("key", authJSON.get("key") + "");
		String nonce = this.findReqtime();
		requestMap.put("nonce", nonce);
		
		requestMap.put("coin", moneytypes[0]);
		requestMap.put("price", paramsMap.get("price") + "");
		requestMap.put("amount", paramsMap.get("amount") + "");
		String type = paramsMap.get("type");
		if(type.equalsIgnoreCase(TradeEnum.TRADE_TYPE_BUY.getValue() + ""))
		{
			type = "buy"; 
		}else if(type.equalsIgnoreCase(TradeEnum.TRADE_TYPE_SELL.getValue() + ""))
		{
			type = "sell"; 
		}
		requestMap.put("type", type);
		
		String signature = authSign(requestMap);
		requestMap.put("signature", signature);
		
		String result = "" ; 
		try
		{
			result = httpUtil.methodPost(Collections.EMPTY_MAP , requestMap);
			//ConstatFinalUtil.SYS_LOG.error(result);
			JSONObject responseJSON = (JSONObject) JSON.parse(result);
			
			JSONObject responseDataJSON = responseJSON.getJSONObject("data");
			if(responseDataJSON !=null)
			{
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("order_id", responseDataJSON.get("id"));
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("msg"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "下单交易返回--原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "下单交易失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 撤销订单
	 * 
	 * @return
	 */
	public JSONObject cancelOrder(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.cancelOrder(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new HashMap<String, String>();
		//转换货币类型
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype"));
		String [] moneytypes = moneytype.split("\\|");
				
		requestMap.put("requestURL", this.serverUrl + "/api/v1/trust_cancel/region/" + moneytypes[1]);
		requestMap.put("key", authJSON.get("key") + "");
		String nonce = this.findReqtime();
		requestMap.put("nonce", nonce);
		
		requestMap.put("id", paramsMap.get("order_id") + "");
		requestMap.put("coin", moneytypes[0]);
		
		String signature = authSign(requestMap);
		requestMap.put("signature", signature);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodPost(Collections.EMPTY_MAP , requestMap);
			responseJSON = (JSONObject) JSON.parse(result);
			
			JSONObject responseDataJSON = responseJSON.getJSONObject("data");
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("order_id", responseDataJSON.get("id"));
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "撤销订单返回.--原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "撤销订单失败."
					+ paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 获取用户挂单
	 * 
	 * @param args
	 */
	public JSONObject getOrders(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.getOrders(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new TreeMap<String, String>();
		//转换货币类型
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype"));
		String [] moneytypes = moneytype.split("\\|");
		
		requestMap.put("requestURL", this.serverUrl + "/api/v1/trust_list/region/" + moneytypes[1]);
		
		requestMap.put("key", authJSON.get("key") + "");
		String nonce = this.findReqtime();
		requestMap.put("nonce", nonce);
		
		requestMap.put("coin", moneytypes[0]);
		requestMap.put("type", "open");
		
		String signature = authSign(requestMap);
		requestMap.put("signature", signature);
		
		String result = "" ; 
		try
		{
			result = httpUtil.methodPost(Collections.EMPTY_MAP , requestMap);
			JSONObject responseJSON = (JSONObject) JSON.parse(result);
			JSONObject dataJSON = new JSONObject();
			
			JSONArray responseDataArr = responseJSON.getJSONArray("data");
			JSONArray ordersResArr = new JSONArray();
			for (Iterator iterator = responseDataArr.iterator(); iterator.hasNext();)
			{
				JSONObject ordersTemp = (JSONObject) iterator.next();
				JSONObject ordersResJSON = this.convertOrders(moneytype, ordersTemp);
				ordersResArr.add(ordersResJSON);
			}
			
			dataJSON.put("ordersList", ordersResArr);
			resultJSON.put("data", dataJSON);
				
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "获取用户挂单.--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户挂单失败."
					+ paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 行情API
	 */
	public JSONObject queryTicker(Map<String, String> paramsMap)
	{

		HTTPUtil httpUtil = new HTTPUtil();
		String symbol = paramsMap.get("symbol");
		if ("ltc_cny".equalsIgnoreCase(symbol))
		{
			paramsMap.put("requestURL",
					"https://www.btctrade.com/api/ticker");
		} else
		{
			paramsMap.put("requestURL", "https://www.btctrade.com/api/ticker");
		}

		paramsMap.remove("symbol");

		JSONObject resultJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(paramsMap);
			resultJSON = (JSONObject) JSON.parse(result);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "行情API失败."
					+ paramsMap + ";原始信息:" + result , e);
		}
		return resultJSON;
	}

	/**
	 * depth(市场深度)
	 * {"asks":[["2108.00000","0.076"],,,],"bids":[["2083.01000","0.300"],,,]}
	 */
	public JSONObject queryDepth(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		
		HTTPUtil httpUtil = new HTTPUtil();
		
		Map<String, String> requestMap = new HashMap<String, String>();
		//转换货币类型
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype"));
		String [] moneytypes = moneytype.split("\\|");

		requestMap.put("requestURL", this.serverUrl + "/api/v1/depth/region/" + moneytypes[1]);
		requestMap.put("coin", moneytypes[0]);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(requestMap);
			//ConstatFinalUtil.SYS_LOG.error(result);
			responseJSON = (JSONObject) JSON.parse(result);
			JSONObject dataResJSON = responseJSON.getJSONObject("data");
			
			// 拼装符合条件的json数据
			JSONObject dataJSON = new JSONObject();

			int count = 0;
			// 按照规则排序的容器
			Map<Double, JSONObject> asksMap = new TreeMap<Double, JSONObject>();
			JSONArray asksResArr = new JSONArray();
			JSONArray asksArr = (JSONArray) dataResJSON.get("asks");
			for (Iterator iterator = asksArr.iterator(); iterator.hasNext();)
			{
				JSONArray asksTempArr = (JSONArray) iterator.next();
				JSONObject askJSON = new JSONObject();
				askJSON.put("count", "1");
				askJSON.put("vol", asksTempArr.get(1) + "");
				askJSON.put("rate", asksTempArr.get(0) + "");

				asksMap.put(Double.valueOf(askJSON.get("rate") + ""), askJSON);
			}

			for (Iterator iterator = asksMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE)
				{
					break;
				}

				JSONObject asksTemp = (JSONObject) me.getValue();

				asksResArr.add(asksTemp);
				count++;
			}

			dataJSON.put("asks", asksResArr);

			// 按照规则排序的容器
			count = 0;
			Map<Double, JSONObject> bidsMap = new TreeMap<Double, JSONObject>(
					new Comparator<Double>()
					{
						@Override
						public int compare(Double o1, Double o2)
						{
							return o2.compareTo(o1);
						}
					});
			JSONArray bidsResArr = new JSONArray();
			JSONArray bidsArr = (JSONArray) dataResJSON.get("bids");
			for (Iterator iterator = bidsArr.iterator(); iterator.hasNext();)
			{
				JSONArray bidsTempArr = (JSONArray) iterator.next();
				JSONObject bidsJSON = new JSONObject();
				bidsJSON.put("count", "1");
				bidsJSON.put("vol", bidsTempArr.get(1) + "");
				bidsJSON.put("rate", bidsTempArr.get(0) + "");

				bidsMap.put(Double.valueOf(bidsJSON.get("rate") + ""), bidsJSON);
			}

			for (Iterator iterator = bidsMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE)
				{
					break;
				}

				JSONObject bidsTemp = (JSONObject) me.getValue();

				bidsResArr.add(bidsTemp);
				count++;
			}
			dataJSON.put("bids", bidsResArr);

			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			resultJSON.put("data", dataJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "depth(市场深度)失败."
					+ paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * trades的格式,历史交易记录
	 */
	public JSONArray queryHistoryTrades(String symbol,
			Map<String, String> paramsMap)
	{
		return null;
	}

	/**
	 * 获取所有的行情
	 * 
	 * @return
	 */
	public JSONObject getTrade()
	{
		return null;
	}

	public void setAuthJSON(JSONObject authJSON)
	{
		this.authJSON = authJSON;
	}

	@Override
	public String convertMoneyType(String moneytype)
	{
		moneytype = moneytype.replaceAll("usdt", "usc");
		return moneytype.replaceAll("_", "|") ; 
	}

	@Override
	public String toString()
	{
		return "BtcTradeTradeServiceImplay [findid()=" + findWebsiteId() + "]";
	}

	@Override
	public JSONObject getOrdersSingle(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.getOrdersSingle(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new TreeMap<String, String>();
		//转换货币类型
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype"));
		String [] moneytypes = moneytype.split("\\|");
		
		requestMap.put("requestURL", this.serverUrl + "/api/v1/trust_view/region/" + moneytypes[1]);
		
		requestMap.put("key", authJSON.get("key") + "");
		String nonce = this.findReqtime();
		requestMap.put("nonce", nonce);
		
		requestMap.put("coin", moneytypes[0]);
		requestMap.put("id", paramsMap.get("order_id"));
		
		String signature = authSign(requestMap);
		requestMap.put("signature", signature);
		String result = "" ; 
		try
		{
			result = httpUtil.methodPost(Collections.EMPTY_MAP , requestMap);
			JSONObject dataJSON = new JSONObject();
			//ConstatFinalUtil.SYS_LOG.error(result);
			JSONObject responseJSON = (JSONObject) JSON.parse(result);
			JSONObject responseDataJSON = responseJSON.getJSONObject("data");
			JSONObject ordersResJSON = this.convertOrders(moneytype, responseDataJSON);
		
			dataJSON.put("orders", ordersResJSON);
			resultJSON.put("data", dataJSON);
			
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "获取订单详情.--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取订单详情失败."
					+ paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	
	}

	@Override
	public String parseMoneyType(String moneytype)
	{
		return null;
	}

	@Override
	public String findWebSiteName()
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public JSONObject convertOrders(String moneytype, JSONObject ordersTempJSON)
	{
		JSONObject ordersResJSON = new JSONObject();
		ordersResJSON.put("order_id", ordersTempJSON.getString("id"));
		ordersResJSON.put("price", ordersTempJSON.getString("price"));
		ordersResJSON.put("create_date", ordersTempJSON.getString("datetime"));
		ordersResJSON.put("amount", ordersTempJSON.getString("amount_total"));
		ordersResJSON.put("deal_amount", Double.valueOf(ordersTempJSON.getString("amount_total")) - Double.valueOf(ordersTempJSON.getString("amount_remain")) + "");
		ordersResJSON.put("symbol", moneytype);
		String type = ordersTempJSON.get("type") + "";
		if("buy".equalsIgnoreCase(type))
		{
			type = TradeEnum.TRADE_TYPE_BUY.getValue() + "" ; 
		}else if("sell".equalsIgnoreCase(type))
		{
			type = TradeEnum.TRADE_TYPE_SELL.getValue() + "" ; 
		}
		ordersResJSON.put("type", type);
		/*  状态：1 （ 新挂单 ） 2 （ 开放交易 ）, 3 （ 撤销 ）, 4 （ 完全成交 ） */
		String status = ordersTempJSON.getString("status");
		if("1".equalsIgnoreCase(status) || "2".equalsIgnoreCase(status))
		{
			status = TradeEnum.TRADE_STATUS_DEAL_NO.getValue() + "" ;
		}else if("3".equalsIgnoreCase(status))
		{
			status = TradeEnum.TRADE_STATUS_CANCEL.getValue() + "" ;
		}else if("4".equalsIgnoreCase(status))
		{
			status = TradeEnum.TRADE_STATUS_DEALED.getValue() + "" ;
		}else
		{
			if(Double.valueOf(ordersResJSON.get("deal_amount") + "") > 0 
				&& Double.valueOf(ordersResJSON.get("deal_amount") + "") < Double.valueOf(ordersResJSON.get("amount") + ""))
			{
				status = TradeEnum.TRADE_STATUS_DEAL_PART.getValue() + "" ;
			}
		}
		ordersResJSON.put("status", status);
		return ordersResJSON;
	}
}
